#include "myfavorites.h"
#include "ui_myfavorites.h"
#include <QDebug>
static QAction *open;
static QAction *del;
static QAction *openinfile;
MyFavorites::MyFavorites(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyFavorites)
{
    ui->setupUi(this);

    connect(FavoriteLib::getInstance(),&FavoriteLib::s_favoriteLoadDone,this,&MyFavorites::loadFavorite);
    ThreadManger::getInstance()->loadFavorite();

}

MyFavorites::~MyFavorites()
{
    delete ui;
}

void MyFavorites::addFavorite(QString filename,QString sendername,QString sendTime)
{
    QListWidgetItem *item=new QListWidgetItem("");
    ui->listWidget->addItem(item);
    FavoriteBox *favoritebox=new FavoriteBox;
    favoritebox->setFileName(filename);
    favoritebox->setSenderName(sendername);
    favoritebox->setSendTime(sendTime);
    ui->listWidget->setItemWidget(item,favoritebox);
    item->setSizeHint(favoritebox->getSize());
    fileboxlist.push_back(favoritebox);
}

void MyFavorites::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    if(ui->listWidget->itemAt(pos)){
        QMenu m(this);
        open=m.addAction("打开文件");
        del=m.addAction("删除");
        openinfile=m.addAction("在文件夹中打开");
        connect(open,&QAction::triggered,this,[=](){
            QFileInfo fileinfo(fileboxlist[ui->listWidget->currentRow()]->getFilePath());
            QDesktopServices::openUrl(fileinfo.absoluteFilePath());
        });
        connect(del,&QAction::triggered,this,[=](){
            removeFavorite(fileboxlist[ui->listWidget->currentRow()]);
        });
        connect(openinfile,&QAction::triggered,this,[=](){
            QFileInfo fileinfo("./FavoriteFile");
            QDesktopServices::openUrl(fileinfo.absoluteFilePath());
        });
        m.exec(QCursor::pos());
    }
    else
    {
       return;
    }
}

void MyFavorites::loadFavorite()
{
    QList<QPair<QPair<QString, QString>, QString> > result=FavoriteLib::getInstance()->getList();
    for(QPair<QPair<QString, QString>, QString> i:result)
    {
        addFavorite(i.first.second,i.first.first,i.second);
    }
}

void MyFavorites::removeFavorite(FavoriteBox * box)
{
    ThreadManger::getInstance()->deleteFile(box->getFilePath());
    ThreadManger::getInstance()->deleteFavoriteDB(box->getFileName());
    QListWidgetItem* targetbox= ui->listWidget->takeItem(ui->listWidget->currentRow());
    delete targetbox;
}
